package com.ebelter.bodyfatscale.moudules.load;


import android.app.Dialog;
import android.content.Context;
import android.text.TextUtils;

import com.ebelter.bodyfatscale.common.Constants;
import com.ebelter.bodyfatscale.moudules.db.DaoInterface;
import com.ebelter.bodyfatscale.moudules.db.Daos;
import com.ebelter.bodyfatscale.moudules.db.beans.HistoryMesureData;
import com.ebelter.bodyfatscale.ui.activity.MainActivity;
import com.ebelter.bodyfatscale.ui.view.dialogs.WeighTipDialog;
import com.ebelter.bodyfatscale.util.NumUtils;
import com.ebelter.bodyfatscale.util.ScaleBaseUtils;
import com.ebelter.bodyfatscale.util.UserSpUtil;
import com.ebelter.btlibrary.btble.impl.scale.model.ScaleMeasureResult;
import com.ebelter.btlibrary.util.ULog;

public class LoadData2Service {


    private static final String TAG = "LoadData2Service";
    private WeighTipDialog mWeighTipDialog;


    private String lastUploadTime;

    public void load(final Context context, final Object tag, ScaleMeasureResult result, boolean isOffData){

        if (result==null){
            return;
        }
        final long userId=UserSpUtil.readLong(Constants.IUser.USER_ID);
        if (userId<=0){
            return;
        }

        if (Constants.isGuestModel|| TextUtils.equals("0",result.getBtId())){
            return;//访客模式不需要上传数据
        }
        if (TextUtils.equals(lastUploadTime,result.getMeasureTime())){
            ULog.i(TAG,"发现两次上传的数据时间是一样的，拒绝上传此次数据");
            return;
        }
        lastUploadTime = result.getMeasureTime();


        result=ScaleBaseUtils.checkScaleMeasureResult18old(result);
        final float weight=numFatmat(result.getWeight());
        if (weight<=0){
            return;//如果体重都等于0时就没必要往上传了
        }
        final float fat=numFatmat(result.getFat());
        final float bmi=numFatmat(result.getBmi());
        final float bmr=numFatmat(result.getBmr());
        final float vf= numFatmat(result.getVisceralFat());//内脂等级
        final float muscleMass=numFatmat(result.getMuscleVolume());
        final float boneMass=numFatmat(result.getBoneVolume());
        final float protein=numFatmat(result.getProtein());
        final float waterRate=numFatmat(result.getWaterRate());
        final float skeletalMuscle=numFatmat(result.getSkeletalMuscle());
        final int bodyScore= (int) result.getBodyScore();
        int bodyAge= (int) result.getBodyAge();



        float currentWeight = UserSpUtil.readFloat(Constants.IUser.WEIGHT);
        if (isOffData&&Math.abs(currentWeight-weight)>=3){
            //如果是离线数据，并且体重差值大于3kg直接摒弃掉
            return;
        }
        if ((!isOffData)&&Math.abs(currentWeight-weight)>=2){//不是离线数据差值在大于2kg 需要弹框
            if (mWeighTipDialog!=null){
                mWeighTipDialog.cancel();
                mWeighTipDialog=null;
            }
            mWeighTipDialog=new WeighTipDialog(context);
            final ScaleMeasureResult finalResult = result;
            mWeighTipDialog.setListener(new WeighTipDialog.ICancelOkBtListener() {
                @Override
                public void cancel(Dialog dialogView) {
                    dialogView.cancel();
                }

                @Override
                public void ok(Dialog dialogView) {
                    dialogView.cancel();
                    upLoadData(context,tag,userId,finalResult,weight,bmi,bmr,fat,vf,muscleMass,boneMass,protein,waterRate,skeletalMuscle,bodyScore);
                }
            });
            mWeighTipDialog.show();
        }else {
            upLoadData(context,tag,userId,result,weight,bmi,bmr,fat,vf,muscleMass,boneMass,protein,waterRate,skeletalMuscle,bodyScore);
        }
    }


    private void upLoadData(final Context context, Object tag, final long userID, final ScaleMeasureResult result, final float weight, final float bmi, final float bmr, final float fat, final float vf,
                            final float muscleMass, final float boneMass, final float protein, final float waterRate, final float skeletalMuscle, int bodyScore){


        HistoryMesureData h = new HistoryMesureData();
        h.userID=userID;
        h.weight=weight;
        h.bmi=bmi;
        h.bmr=bmr;
        h.fat=fat;
        h.visceralFat=vf;
        h.muscleVolume=muscleMass;
        h.boneVolume=boneMass;
        h.protein=protein;
        h.waterRate=waterRate;
        h.skeletalMuscle=skeletalMuscle;
        h.bodyScore=bodyScore;
        h.bodyAge= (int) result.getBodyAge();
        h.measureTime = result.getMeasureTime();
        h.save();


        //保存数据成功后 计算当天数据的平均值
        Daos.getInstance().computeTodayData(h.userID, h.measureTime, new DaoInterface.Calculate() {
            @Override
            public void Complete() {
                //计算当天数据的平均值完成 请求趋势界面的的平均值
                if (context!=null&&context instanceof MainActivity){
                    ((MainActivity)context).trendPagerRequestAvgData();//请求一下趋势页面的平均数据
                }
            }
        });




    }


    private float numFatmat(float num){
        return NumUtils.numBaoLiuWei(num,1);
    }


    //检测上传离线数据
//    public void checkUpLoad(Object tag){
//        if (!NetUtils.available()){
//            return;
//        }
//        final long userId=UserSpUtil.readLong(Constants.IUser.USER_ID);
//        if (userId<=0){
//            return;
//        }
//        final HistoryMesureData historyMesureData = new Select().from(HistoryMesureData.class).where(HistoryMesureData_Table.userID.eq(userId)).querySingle();
//        if (historyMesureData==null){
//            ULog.i(TAG,"-----数据库没有要上传的数据：");
//            return;
//        }
//        ULog.i(TAG,"准备上传数据库保存的数据："+historyMesureData.toString());
//        Map<String,Serializable> paramMap=new HashMap<>();
//        paramMap.put(HttpsParameters.USER_ID, userId);
//        paramMap.put(HttpsParameters.WEIGHT, historyMesureData.weight);
//        paramMap.put(HttpsParameters.BMI, historyMesureData.bmi);
//        paramMap.put(HttpsParameters.BMR, historyMesureData.bmr);
//        //  paramMap.put(HttpsParameters.VISCERAL_FAT, fat);//脂肪率
//        paramMap.put(HttpsParameters.ADIPOSE_RATE, historyMesureData.fat);//脂肪率
//        paramMap.put(HttpsParameters.VISCERAL_FAT, historyMesureData.visceralFat);//内脂等级
//        paramMap.put(HttpsParameters.MUSCLEQUANTITY, historyMesureData.muscleVolume);
//        paramMap.put(HttpsParameters.BONEMASS, historyMesureData.boneVolume);
//        paramMap.put(HttpsParameters.PROTEIN, historyMesureData.protein);
//        paramMap.put(HttpsParameters.MOISTURE, historyMesureData.waterRate);//水分
//        paramMap.put(HttpsParameters.BONEMINERALCONTENT, historyMesureData.skeletalMuscle);//骨骼肌
//        paramMap.put(HttpsParameters.BODY_SOCRE, historyMesureData.bodyScore);
//        paramMap.put(HttpsParameters.PHYSICA_AGE, historyMesureData.bodyAge);
//        paramMap.put(HttpsParameters.TEST_DATE, historyMesureData.measureTime);
//        NetUtils.getInstance().uploadData(tag, paramMap, new HttpResponse<OriginalParametersResponse>() {
//            @Override
//            public void result(boolean isRequestSuccess, String requestDes, OriginalParametersResponse originalParametersResponse) {
//
//                if (isRequestSuccess){
//                    if (originalParametersResponse.resultCode==0){
//                        ULog.i(TAG,"--数据库---上传测量1数据----上传成功---");
//                        historyMesureData.delete();
//                    }else {
//                        ULog.i(TAG,"--数据库---上传测量1数据----上传失败："+originalParametersResponse.resultMessage);
//                    }
//                }else {
//                    ULog.i(TAG,"--数据库---上传测量1数据----网络失败");
//                }
//
//            }
//        });
//
//    }


}
